import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/auth/LoginView.vue'
import DataSelectView from '@/views/data/DataSelectView.vue'
import DataView from '@/views/data/DataView.vue'
import GameSelectView from '@/views/game/GameSelectView.vue'
import Part1GameView from '@/views/game/part1/Part1GameView.vue'
import Part2DifficultySelectView from '@/views/game/part2/Part2DifficultySelectView.vue'
import Part2GameView from '@/views/game/part2/Part2GameView.vue'
import Part3DifficultySelectView from '@/views/game/part3/Part3DifficultySelectView.vue'
import Part3GameView from '@/views/game/part3/Part3GameView.vue'
import { checkLogin } from '../utils/auth.js'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/:pathMatch(.*)*',
      redirect: { name: 'home' }
    },
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/data-select',
      name: 'data-select',
      component: DataSelectView
    },
    {
      path: '/data',
      name: 'data',
      component: DataView
    },
    {
      path: '/game-select',
      name: 'game-select',
      component: GameSelectView
    },
    {
      path: '/part1-game',
      name: 'part1-game',
      component: Part1GameView
    },
    {
      path: '/part2-difficulty-select',
      name: 'part2-difficulty-select',
      component: Part2DifficultySelectView
    },
    {
      path: '/part2-game',
      name: 'part2-game',
      component: Part2GameView
    },
    {
      path: '/part3-difficulty-select',
      name: 'part3-difficulty-select',
      component: Part3DifficultySelectView
    },
    {
      path: '/part3-game',
      name: 'part3-game',
      component: Part3GameView
    }
  ]
})

router.beforeEach((to, from) => {
  // part2、3 中如果不是从难度选择界面进入游戏界面，则跳转到游戏选择界面
  // 如果在不是从游戏选择界面进入难度选择界面，则跳转到游戏选择界面
  // part1 如果不是从游戏选择界面进入游戏界面，则跳转到游戏选择界面
  if (to.name === 'part1-game' && from.name !== 'game-select') {
    return { name: 'game-select' }
  }
  if (to.name === 'part2-game' && from.name !== 'part2-difficulty-select') {
    return { name: 'game-select' }
  }
  if (to.name === 'part3-game' && from.name !== 'part3-difficulty-select') {
    return { name: 'game-select' }
  }
  if (
    (to.name === 'part2-difficulty-select' || to.name === 'part3-difficulty-select') &&
    from.name !== 'game-select'
  ) {
    return { name: 'game-select' }
  }
  if (to.name === 'login') {
    // 如果已经登录了再去访问login，那就直接跳转到home
    return checkLogin() ? { name: 'home' } : true
  }
  return checkLogin() || to.name === 'login' || { name: 'login' }
})

export default router
